#include <iostream>
#include <unistd.h>
#include <cstring>
#include <sys/types.h>
#include <sys/wait.h>
#include <cassert>

using namespace std;

int main() {
    int pipefd[2];
    int ret = pipe(pipefd);
    assert(ret == 0);

    pid_t pid = fork();

    if (pid == 0) {
        // 子进程：只读
        close(pipefd[1]); // 关闭写端

        char buff[64];
        while (true) {
            int n = read(pipefd[0], buff, sizeof(buff) - 1); // 留一个字节放 '\0'
            if (n > 0) {
                buff[n] = '\0';
                cout << "成功读取到信息: " << buff << endl;
            } else if (n == 0) {
                // 写端关闭，read返回0
                cout << "写端已关闭，读取数据量为: " << n << " 字节" << endl;
                
            } else {
                perror("read error");
                break;
            }

            sleep(1);
        }

        close(pipefd[0]); // 关闭读端
        exit(0);
    } else {
        // 父进程：只写
        close(pipefd[0]); // 关闭读端

        char buff[] = "Hello pipe!";
        write(pipefd[1], buff, strlen(buff)); // 写入数据
        cout << "父进程已写入数据: " << buff << endl;

        close(pipefd[1]); // 关闭写端
        cout << "父进程已关闭写端" << endl;

        waitpid(pid, nullptr, 0); // 等待子进程结束
    }

    return 0;
}

